package com.ridbor001.demo.servlet;

import com.ridbor001.demo.service.RDBStudentService;
import com.ridbor001.demo.service.RDBTeacherService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;


@WebServlet("/checkUnique")
public class RDBUniqueCheckServlet extends HttpServlet {
    RDBStudentService rdbStudentService = new RDBStudentService();
    RDBTeacherService rdbTeacherService = new RDBTeacherService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        String role = request.getParameter("role");
        String id = request.getParameter("id");
        boolean isValid = false;
        String message = "";

        try {
            if ("student".equals(role)) {
                // 检查学号是否唯一
                isValid = !rdbStudentService.studentExists(id);
                message = isValid ? "" : "学号已存在！";
            } else if ("teacher".equals(role)) {
                // 检查教师ID是否唯一
                isValid = !rdbTeacherService.teacherExists(id);
                message = isValid ? "" : "工号已存在！";
            } else {
                // 无效的角色
                message = "无效的用户类型！";
            }
        } catch (SQLException e) {
            // 数据库错误处理
            isValid = false;
            message = "系统错误，请稍后再试！";
            e.printStackTrace(); // 记录错误日志
        }

        // 返回JSON响应
        response.getWriter().write(
                String.format("{\"valid\":%s, \"message\":\"%s\"}",
                        String.valueOf(isValid).toLowerCase(), // true/false
                        escapeJsonString(message))
        );
    }

    // 转义JSON字符串中的特殊字符
    private String escapeJsonString(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("/", "\\/")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}